//https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool findIntree(TreeNode* root,TreeNode* x)
    {
        if(root == nullptr)
        {
            return false;
        }
        return root == x || findIntree(root->right, x) || findIntree(root->left, x);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr || root == p || root == q) return root;
        bool pinleft = findIntree(root->left, p);
        bool pinright = !pinleft;

        bool qinright = findIntree(root->right, q);
        bool qinleft = !qinright;

        if((pinleft && qinright) || (pinright && qinleft)) return root;
        else if(pinright && qinright) return lowestCommonAncestor(root->right, p, q);
        else return lowestCommonAncestor(root->left, p, q);
    }
};

    //方法二，通过栈的方法获取路径
    bool getpath (TreeNode* root, TreeNode* x, stack<TreeNode*>& path)
    {
        if(root == nullptr) return false;
        
        path.push(root);
        if(root == x) return true;
        if(getpath(root->left, x, path)) return true;
        if(getpath(root->right, x, path)) return true;
        path.pop();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> ppath, qpath;
        getpath(root, p, ppath);
        getpath(root, q, qpath);
        while(ppath.size() != qpath.size())
        {
            if(ppath.size() > qpath.size()) ppath.pop();
            else qpath.pop();
        }
        while(ppath.top() != qpath.top())
        {
            ppath.pop();
            qpath.pop();
        }
        return ppath.top();
    }